# -*- coding:utf-8 -*-
import imp
from STool.StockFileManager import StockFileManager
from STool.StockTool import StockTool
from SDaily.StockTushare import StockTushare

class StockYearHigh:
    def __init__(self,sql_obj):
        self.sql_obj=sql_obj
        pass
    

    def yearHighBarJson(self,labels,labels_data,sum):
        
        select_labels=[]
        for index,label in enumerate(labels):
            select_labels.append({'label':label,'value':index})
        
        yearHightJson={
            "select_labels":select_labels,
            "chartdata":{
                "labels":labels,
                "datasets":[
                    {
                        "borderColor": "rgb(44, 147, 255)", 
                        "label": "一年新高个数："+str(sum), 
                        "borderWidth": 1, 
                        "barThickness":10,
                        "backgroundColor": "rgb(44, 147, 255,0.5)", 
                        "fill": False,
                        "data":labels_data
                    }
                ]
            },
            "options": {
                "stacked": False, 
                "maintainAspectRatio": False, 
                "scales": {
                "yAxes": [
                    {
                    "ticks": {
                        "fontSize": 8, 
                        "beginAtZero": True
                    }
                    }
                ]
                }, 
                "responsive": True, 
                "layout": {
                "padding": {
                    "left": 10,
                    "right": 10,
                    "top": 0,
                    "bottom": 0
                }
                },
                "hoverMode": "index" 
            }
        }
        return yearHightJson
        # StockFileManager.rewriteDataToFile(yearHightJson,"yearHigh")
        
    
    def yearHighBarTableJson(self,tableJson):
        StockFileManager.rewriteDataToFile(tableJson,"yearHigh_table")

    
    def getNewHighData(self,key,all_cal_date,fileName):
        
        all_date_high_json={}
        all_date_high_table_json={}
        for index,cal_date in enumerate(all_cal_date):
            myquery={"trade_daily": { "$elemMatch":{"isYearHigh": 1, "trade_date":cal_date}},"ts_code": {"$regex":"(?<!.BJ)$"},"list_date_days":{"$gte":365},"circ_mv":{"$gte":50}}
            stocks=self.sql_obj.sql(myquery)
            source_stocks=[]
            for item in stocks:
                source_stocks.append(item)
                
            if len(source_stocks) <1:
                continue
            yearHigh_stocks=[]
            for itema in source_stocks:
                close=itema['trade_daily'][0]['close']
                itema['close']=str(close)+"元"
                itema.pop('list_date')
                itema.pop('symbol')
                itema.pop('_id')
                itema.pop('trade_daily')
                itema['close']=str(close)+"元"
                if 'hk_ORG' in list(itema.keys()):
                    hk_ORG=int(itema['hk_ORG'])/1000
                    if hk_ORG>0:
                        itema['hk_ORG']=str(hk_ORG)+"万股"
                    else:
                        itema['hk_ORG']=str(0)
                yearHigh_stocks.append(itema)
            
            
            yearHigh_bankuai_stocks= StockTool.remakeStocksGroupByBK(yearHigh_stocks,"hy")
            labels = list(yearHigh_bankuai_stocks.keys())
            labels_data={}
            sum=0
            for label in labels:
                count = len(yearHigh_bankuai_stocks[label])
                labels_data[label]=count
                sum+=count
            
            labels_data = sorted(list(labels_data.items()), key=lambda item:item[1] ,reverse = True)
            json_labels=[item[0] for item in labels_data]
            json_labels_data=[item[1] for item in labels_data]
            
            
            yearHightJson = self.yearHighBarJson(json_labels,json_labels_data,sum)
            all_date_high_json[cal_date]=yearHightJson
            all_date_high_table_json[cal_date]=yearHigh_bankuai_stocks
            
        StockFileManager.rewriteDataToFile(all_date_high_json,fileName)
        StockFileManager.rewriteDataToFile(all_date_high_table_json,fileName+"_table")
    
    def remarkYearHigh(self):
        tushareObj=StockTushare()
        df = tushareObj.pro.trade_cal(exchange='', start_date='20210101', end_date=tushareObj.today_mt_string,is_open="1")
        all_date = df.to_dict('records')
        #取最近10日交易日
        all_date = sorted(all_date,key = lambda e:e.__getitem__('cal_date'), reverse=True)[0:10]
        all_cal_date=[item['cal_date'] for item in all_date]
        mtkeys=["isYearHigh"]
        fileNames=["t_250_high"]
       
        for index,key in enumerate(mtkeys):
            self.getNewHighData(key,all_cal_date,fileNames[index])
            
        